import React, { FC, memo, ReactNode, useEffect, useState } from 'react'
import { Outlet } from 'react-router-dom'
import { Layout, theme } from 'antd'

import MainHeader from '@/views/main/c-cpns/main-header'
import MainMenu from '@/views/main/c-cpns/main-menu'
import { useMyDispatch } from '@/store'
import { fetchInitialUserData } from '@/store/module/app'
import { MainWrapper } from '@/views/main/style'
import { otherRoutes } from '@/router'
import { localCache } from '@/utils/cache'
import { CacheType } from '@/global/constant'
import { mapMenusToRoutes } from '@/utils/menu-handle'

interface IProps {
  children?: ReactNode
}

const Main: FC<IProps> = (props) => {
  const dispatch = useMyDispatch()
  const [collapsed, setCollapsed] = useState(false)
  const {
    token: { colorBgContainer }
  } = theme.useToken()

  useEffect(() => {
    // 初始化用户数据，菜单、权限、右上角个人信息
    dispatch(fetchInitialUserData()).then(() => {
      const menuList = localCache.getCache(CacheType.MENU_LIST)
      const newRoutes = mapMenusToRoutes(menuList, otherRoutes)
      // const newRoutes = mapMenusToRoutes(menuList[0].children, otherRoutes)
      localCache.setCache(CacheType.ROUTES, newRoutes)
    })
  }, [])

  /* 回调 */
  function handleCollapseClick(isCollapsed: boolean) {
    setCollapsed(isCollapsed)
  }

  return (
    <MainWrapper colorBgContainer={colorBgContainer}>
      <Layout style={{ height: '100%' }}>
        <Layout.Sider
          theme="light"
          trigger={null}
          collapsible
          collapsed={collapsed}
        >
          <MainMenu collapsed={collapsed} />
        </Layout.Sider>
        <Layout style={{ height: '100%' }}>
          <MainHeader onCollapseClick={handleCollapseClick} />
          <Layout.Content className="content">
            <Outlet />
          </Layout.Content>
        </Layout>
      </Layout>
    </MainWrapper>
  )
}

export default memo(Main)
